package com.webserver.core;

import jdk.internal.util.xml.impl.Input;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;

/**
 * 线程任务
 * 负责与特定的客户端进行HTTP交互
 */
public class ClientHandler implements Runnable{
    private Socket socket;

    public ClientHandler(Socket socket){
        this.socket = socket;
    }
    public void run() {
        try {
            //http://localhost:8088/
            //1、解析请求
            InputStream in = socket.getInputStream();
            StringBuilder builder = new StringBuilder();
            char cur = 'a';//保存本次读取到的字符
            char pre = 'a';//保存上次读取到的字符
            int d;
            while ((d = in.read())!= -1){
                cur = (char)d;
                if (pre==13 && cur==10) {
                    //判断是否连续读取到回车+换行
                    break;
                }
                builder.append(cur);
                pre = cur;
                //System.out.print((char)d);
            }
            String line = builder.toString().trim();
            System.out.println("请求行："+line);
            String method;//请求方式
            String url;//抽象路径
            String protocol;//协议版本
            String[] data = line.split("\\s");
            method = data[0];
            System.out.println("method:"+method);
            url = data[1];
            System.out.println("url:"+url);
            protocol = data[2];
            System.out.println("protocol:"+protocol);
            //2、处
            // 理请求
            //3、发送响应
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                //响应后断开连接
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }
}
